package com.xaehu.kotlinstudy;

import android.annotation.SuppressLint;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class WebActivity extends AppCompatActivity {
    private final String TAG = "WebActivity";
    private WebView webView;
    private TextView tv;
    private EditText etUrl;
    private Button btnGo;
    private LinearLayout webLin;


    @SuppressLint({"AddJavascriptInterface", "SetJavaScriptEnabled"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        tv = findViewById(R.id.tv);
        webLin = findViewById(R.id.lin_web);
        etUrl = findViewById(R.id.et_url);
        btnGo = findViewById(R.id.btn_go);
        etUrl.setText("www.baidu.com");
        addWebView();
        initWebSetting();
        initListener();
    }

    private void initListener() {
        btnGo.setOnClickListener(v -> {
            String url = etUrl.getText().toString();
            if(!url.startsWith("http")){
                url = "https://"+url;
            }
            webView.loadUrl(url);
        });

        btnGo.setOnLongClickListener(v -> {
            etUrl.setText("");
            return true;
        });
    }

    @SuppressLint("AddJavascriptInterface")
    private void addWebView() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        webView = new WebView(getApplicationContext());
        webView.setLayoutParams(params);
        webLin.addView(webView);
        webView.addJavascriptInterface(new InJavaScriptLocalObj(),"java_obj");
        webView.setWebViewClient(webViewClient);
    }

    private WebViewClient webViewClient = new WebViewClient(){

        @Override
        public void onPageFinished(WebView view, String url) {
            // 在结束加载网页时会回调
            Log.i(TAG, "onPageFinished: "+url);
            etUrl.setText(url);
            // 获取页面内容
            view.loadUrl("javascript:window.java_obj.showSource("
                    + "document.getElementsByTagName('html')[0].innerHTML);");

            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            // 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
            super.onReceivedError(view, errorCode, description, failingUrl);
            tv.setText(description);
            Log.i(TAG, "onReceivedError: description:"+description);
            Log.i(TAG, "onReceivedError: failingUrl:"+failingUrl);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            // handler.cancel();// Android默认的处理方式
            handler.proceed();// 接受所有网站的证书
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view,
                                                          WebResourceRequest request) {
            // 在每一次请求资源时，都会通过这个函数来回调
            return super.shouldInterceptRequest(view, request);
        }
    };

    public final class InJavaScriptLocalObj{
        @JavascriptInterface
        public void showSource(String html) {
            html = html.replaceAll(">",">\n\t");
            html = html.replaceAll("</","\n</");
            Log.i(TAG, "showSource: \n"+html);
            final String text = html;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv.setText(text);
                }
            });
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebSetting() {
        WebSettings webSettings = webView.getSettings();

        webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);   //设置页面默认缩放密度
        webSettings.setDefaultTextEncodingName("UTF-8");              //设置默认的文本编码名称，以便在解码html页面时使用
        webSettings.setAllowContentAccess(true);                      //启动或禁用WebView内的内容URL访问
        webSettings.setAppCacheEnabled(false);                        //设置是否应该启用应用程序缓存api
        webSettings.setBuiltInZoomControls(false);                    //设置WebView是否应该使用其内置的缩放机制
        webSettings.setUseWideViewPort(true);                         //设置WebView是否应该支持viewport
        webSettings.setLoadWithOverviewMode(true);                    //不管WebView是否在概述模式中载入页面，将内容放大适合屏幕宽度
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);          //重写缓存的使用方式
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);   //告知js自动打开窗口
        webSettings.setLoadsImagesAutomatically(true);                //设置WebView是否应该载入图像资源
        webSettings.setAllowFileAccess(true);                         //启用或禁用WebView内的文件访问
        webSettings.setDomStorageEnabled(true);                       //设置是否启用了DOM存储API,
        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        //支持js
        webSettings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        webView.onPause();
        webView.pauseTimers();
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
        webView.resumeTimers();
    }

    @Override
    protected void onDestroy() {
        webLin.removeView(webView);
        if (webView != null) {
            webView.clearHistory();
            ((ViewGroup) webView.getParent()).removeView(webView);
            webView.loadUrl("about:blank");
            webView.stopLoading();
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

}
